package controllers

import (
	"gin-students-surrealdb/models"
	"gin-students-surrealdb/repositories"
	"github.com/gin-gonic/gin"
	"net/http"
)

type StudentController struct {
	repo *repositories.StudentRepository
}

func NewStudentController(repo *repositories.StudentRepository) *StudentController {
	return &StudentController{repo: repo}
}

func (c *StudentController) CreateStudent(ctx *gin.Context) {
	var student models.Student
	if err := ctx.ShouldBindJSON(&student); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	createdStudent, err := c.repo.Create(&student)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusCreated, createdStudent)
}

func (c *StudentController) GetAllStudents(ctx *gin.Context) {
	students, err := c.repo.GetAll()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, students)
}

func (c *StudentController) GetStudent(ctx *gin.Context) {
	id := ctx.Param("id")
	student, err := c.repo.GetByID(id)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "Student not found"})
		return
	}

	ctx.JSON(http.StatusOK, student)
}

func (c *StudentController) UpdateStudent(ctx *gin.Context) {
	id := ctx.Param("id")

	var student models.Student
	if err := ctx.ShouldBindJSON(&student); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	updatedStudent, err := c.repo.Update(id, &student)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, updatedStudent)
}

func (c *StudentController) DeleteStudent(ctx *gin.Context) {
	id := ctx.Param("id")
	if err := c.repo.Delete(id); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusNoContent, nil)
}
